首先,在畫面上新增一個按鈕,點了可以導頁
修改app.component.html
<router-outlet></router-outlet>
<button routerLink="store">點我導到store page</button>
window.location
- Javascript 作法 goStore(): void {
window.location.href = '/store'
// 或者 window.location.assign('/store');
// 或者 location.href = '/store';
}
這個方法不藉由
Router
而是透過Javascript
原生方式,會刷新頁面通常會用來導向外部網頁
ex:window.location.href = 'https://google.com.tw'
navigateByUrl
- Router 作法注入Router
服務來導頁
修改app.component.ts
...
constructor(private router: Router) {
}
goStore(): void {
this.router.navigateByUrl('store');
// 或者 this.router.navigate(['store']);
}
routerLink
- Router 作法修改app.component.html
<router-outlet></router-outlet>
<button routerLink="store">點我導到store page</button>
字串
ex: ".../role/id/6556
" 參數以路徑形式帶入key=value
ex: ".../role?id=6556
" 或稱Query String
字串
,用來定位呈現的區塊routerLink
- 樣板帶參數修改app.component.html
<router-outlet></router-outlet>
<a [routerLink]="['role', '6556']">點我進role</a>
若帶入物件的話會出現分號
<a [routerLink]="['/role/1', { atk: 10 }]">點我進role</a>
router.navigate
- 程式帶參數修改app.component.ts
...
constructor(private router: Router) {
}
goRole(): void {
this.router.navigate(['role', '6556']);
}
queryParams
- 樣板帶參數修改app.component.html
<router-outlet></router-outlet>
<button [routerLink]="pages[0]" [queryParams]="pages">點我進store</button>
<a [routerLink]="['role']" [queryParams]="abilityScore">點我進role</a>
修改app.component.ts
,新增對應的成員(member)
export class AppComponent {
title = 'project04';
pages = ['store', 'role']
abilityScore = {'atk': 15, 'def': 6} // 能力值
constructor() {
}
}
點擊按鈕切換分頁時,可以看到隨之帶的物件參數
以Key-Value的形式夾帶在URL中
atk=15&def=6
0=store&1=role
router.navigate
- 程式帶參數修改app.component.ts
constructor(private router: Router) {
}
goRole(): void {
this.router.navigate(['role', '6556'], {queryParams: {'atk': 123, 'def': 44}});
// 或者
// let extras: NavigationExtras = {
// queryParams: {'atk': 123, 'def': 44}
// }
// this.router.navigate(['role', '6556'], extras);
}
fragment
- 樣板帶參數修改app.component.html
<router-outlet></router-outlet>
<a [routerLink]="['role']" [fragment]="'theme'">點我進role</a>
router.navigate
- 程式帶參數修改app.component.ts
...
constructor(private router: Router) {
}
goRole(): void {
this.router.navigate(['role'], {fragment: 'theme'});
}